<template>
  <view class="index">
    <view class="banner-container">
      <!--      <view class="floating-title">首页</view>-->
      <view class="swiper-wrapper">
        <u-swiper mode="none" :list="bannerList" border-radius="0" height="760"></u-swiper>
      </view>
    </view>
    <view class="category-section">
      <view class="section-header">
        <text class="label bold label-title">回收类别</text>
        <text class="label alert-label">可打包在一起回收哦</text>
      </view>
      <view class="category-list">
        <u-grid :col="4" class="category-item" :border="false">
          <u-grid-item v-for="item in categoryList" :key="item.id">
            <view @click="userStore?.userInfo?.type_id != 2 && navigateToDetail(item.id)" class="column">
              <image :src="item.image" mode="aspectFill"/>
              <text class="bold">{{ item.cate_name }}</text>
            </view>
          </u-grid-item>
        </u-grid>
      </view>
    </view>

    <!-- 快速入口 -->
    <view class="quick-action" v-if="userStore?.userInfo?.type_id == 2">

      <view @tap="navigateToOrder()" class="go-recycle-button">去回收</view>
    </view>
    <view class="quick-action" v-else>
      <view
          class="quick-action-button"

          @tap="navigateToRecycle(1)"
          :style="backQuickStyle"
      ></view>
    </view>

    <!-- 回收流程 -->
    <view class="process-section">
      <view class="process-title">回收流程</view>
      <view class="process-list">
        <u-grid :col="4" class="process-item" :border="false">
          <u-grid-item>
            <view class="row-between">
              <view class="column-center">
                <image :src="imageUrl.yuyue" mode="aspectFill"></image>
                <view class="grid-text">在线预约</view>
              </view>
              <view class="grid-right-icon">
                <u-icon name="arrow-right" class="row-center"/>
              </view>
            </view>
          </u-grid-item>
          <u-grid-item>
            <view class="row-between">
              <view class="column-center">
                <image :src="imageUrl.shangmen" mode="aspectFill"></image>
                <view class="grid-text">免费上门</view>
              </view>
              <view class="grid-right-icon">
                <u-icon name="arrow-right" class="row-center"/>
              </view>
            </view>
          </u-grid-item>
          <u-grid-item>
            <view class="row-between">
              <view class="column-center">
                <image :src="imageUrl.wancheng" mode="aspectFill"></image>
                <view class="grid-text">订单完成</view>
              </view>
              <view class="grid-right-icon">
                <u-icon name="arrow-right" class="row-center"/>
              </view>
            </view>
          </u-grid-item>
          <u-grid-item>
            <view class="row-between">
              <view class="column-center">
                <image :src="imageUrl.shouyi" mode="aspectFill"></image>
                <view class="grid-text">获取收益</view>
              </view>
              <view class="grid-right-icon"></view>
            </view>
          </u-grid-item>
        </u-grid>
      </view>
    </view>

    <!-- 常见问题 -->
    <view class="faq-section">
      <view class="faq-header">
        <text class="label bold label-title">常见问题</text>
      </view>
      <u-collapse>
        <u-collapse-item
            v-for="(item, index) in articleList"
            :key="index"
            title="item.title"
            :open="item.isOpen"
        >
          <template v-slot:title>
            <view class="title-box">
              <u-icon name="question-circle-fill" :size="32" color="#aeb3bd"/>
              {{ item.title }}
            </view>
          </template>
          <view class="show-box"> {{ item.description }}</view>
        </u-collapse-item>
      </u-collapse>
    </view>
    <!-- 返回顶部按钮 -->
    <u-back-top
        :scroll-top="scrollTop"
        :top="100"
        :customStyle="{
                backgroundColor: '#FFF',
                color: '#000',
                boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
            }"
    >
    </u-back-top>

    <!--  #ifdef MP  -->
    <!--  微信小程序隐私弹窗  -->
    <MpPrivacyPopup></MpPrivacyPopup>
    <!--  #endif  -->
    <tabbar/>
  </view>
</template>

<script setup lang="ts">
import {getBanner, getCateList, getIndex} from '@/api/shop'
import {onLoad, onPageScroll, onShow} from '@dcloudio/uni-app'
import {computed, onMounted, reactive, ref} from 'vue'
import {useAppStore} from '@/stores/app'
import {useUserStore} from '@/stores/user'
import config from '@/config'

const {getImageUrl} = useAppStore()
const userStore = useUserStore()
// #ifdef MP
import MpPrivacyPopup from './component/mp-privacy-popup.vue'
// #endif

const appStore = useAppStore()
const state = reactive<{
  pages: any[]
  meta: any[]
  article: any[]
  bannerImage: string
}>({
  pages: [],
  meta: [],
  article: [],
  bannerImage: ''
})
const scrollTop = ref<number>(0)
const percent = ref<number>(0)


// 模拟后台返回的banner数据
const bannerList = ref([])

const backQuickStyle = ref({
  backgroundImage: `url(${config.baseUrl}/static/images/quick-action-button.png)`
})

const imageUrl = ref({
  yuyue: config.baseUrl + '/static/images/yuyue.png',
  shangmen: config.baseUrl + '/static/images/shangmen.png',
  wancheng: config.baseUrl + '/static/images/wancheng.png',
  shouyi: config.baseUrl + '/static/images/shouyi.png',
  alertImg: config.baseUrl + '/static/images/alert_icon.png'
})

const getBannerList = async () => {
  console.log(userStore.userInfo)
  try {
    const data = await getBanner()

    if (!Array.isArray(data)) {
      console.warn('getBanner 返回非数组数据:', data)
      return
    }

    // 过滤无效数据后统一构建列表
    const validBanners = data
        .filter((item) => item && item.image)
        .map((item) => getImageUrl(item.image))

    bannerList.value = validBanners
  } catch (error) {
    console.error('获取 banner 列表失败:', error)
    // uni.showToast({ title: '加载 Banner 失败', icon: 'none' })
  }
}

// 模拟后台返回的分类数据
const categoryList = ref([])

const getCategoryList = async () => {
  try {
    const data = await getCateList()
    if (!Array.isArray(data)) {
      console.warn('getBanner 返回非数组数据:', data)
      return
    }

    data.forEach((item) => {
      item.image = getImageUrl(item.ico_image)
    })
    categoryList.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // uni.showToast({ title: '加载分类列表失败', icon: 'none' })
  }
}

const articleList = ref([])
// 获取真实数据（保留原始逻辑）
const getData = async () => {
  try {
    const data = await getIndex()
    // 校验数据有效性并深拷贝
    const validData = Array.isArray(data) ? JSON.parse(JSON.stringify(data)) : []

    validData.map((item, index) => {
      if (index === 0) {
        item.isOpen = true
      }
      return item // 确保 map 返回新数组
    })

    articleList.value = validData
  } catch (error) {
    console.error('获取数据失败:', error)
    articleList.value = [] // 异常时赋默认值
  }
}

// 页面滚动事件
onPageScroll((event: any) => {
  scrollTop.value = event.scrollTop
  const top = uni.upx2px(100)
  percent.value = event.scrollTop / top > 1 ? 1 : event.scrollTop / top
})

// 页面加载
onLoad(() => {
  getData()
  getBannerList()
  getCategoryList()
})

// 跳转到回收页面
const navigateToRecycle = () => {
  uni.navigateTo({url: '/pages/recycle/index'})
}

const navigateToOrder = () => {
  uni.navigateTo({url: '/pages/other_order/order'})
}


// 分类详情跳转（可根据业务需求扩展）
const navigateToDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages/recycle/index?type_id=${item.id}`
  })
}

// 分享给朋友
const onShareAppMessage = (res) => {
  if (res.from === 'button') {
    // 来自页面内分享按钮
    console.log(res.target)
  }
  return {
    title: config.title,
    path: '/pages/index/index',
    imageUrl: '' // 可以设置分享图片
  }
}

// 分享到朋友圈
const onShareTimeline = () => {
  return {
    title: config.title,
    query: '',
    imageUrl: ''
  }
}
</script>

<style lang="scss" scoped>
.index {
  position: relative;
  background-color: #f7f7f7;
  background-repeat: no-repeat;
  background-size: 100% auto;
  overflow: hidden;
  width: 100%;
  transition: all 1s;
  min-height: calc(100vh - env(safe-area-inset-bottom));
}

.banner-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

//.floating-title {
//  position: absolute;
//  top: 44rpx;
//  left: 50%;
//  padding: 20rpx 0;
//  width: 100%;
//  max-width: 600rpx;
//  transform: translate(-50%, -50%);
//  text-align: center;
//  font-size: 36rpx;
//  font-weight: bold;
//  color: #fff;
//  z-index: 10;
//  text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.6);
//}

.swiper-wrapper {
  position: relative;
  z-index: 1;
}

.category-section {
  position: relative;
  padding: 20rpx;
  background-color: #fff;
  z-index: 999;
  margin: -300rpx 20rpx 20rpx 20rpx;
  border-radius: 16rpx;
}

.section-header {
  margin-top: 20rpx;
  margin-bottom: 20rpx;

  .label {
    font-size: 28rpx;
  }

  .label-title {
    margin-left: 10rpx;
  }

  .alert-label {
    border: 0.1rpx solid #236af6;
    background: #f6f9ff;
    color: #236af6;
    font-size: 20rpx;
    padding: 5rpx;
    border-radius: 6rpx;
    margin-left: 20rpx;
  }
}

.category-list {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0 20rpx;
}

.category-item {
  margin-right: 20rpx;
  text-align: center;
  font-size: 26rpx;
  flex-shrink: 0;

  image {
    width: 110rpx;
    height: 80rpx;
    border-radius: 16rpx;
    margin-bottom: 10rpx;
  }
}

.quick-action {
  padding: 0 20rpx 20rpx;
}

.process-section {
  margin: 0 20rpx 20rpx;
  height: auto; /* 设置固定高度 */
  background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
  background-color: #ffffff;
  background-repeat: no-repeat;
  background-size: 100% 30%;
  padding: 0 20rpx;
  border-radius: 16rpx;

  .process-title {
    display: flex;
    font-weight: bold;
    padding-top: 40rpx;
    margin-left: 10rpx;
  }

  .process-list {
    display: flex;
    margin-top: 20rpx;

    .process-item {
      text-align: center;
      font-size: 26rpx;
      flex-shrink: 0;

      image {
        width: 80rpx;
        height: 80rpx;
      }

      .grid-text {
        margin-top: 20rpx;
        color: #000000;
        font-weight: 400;
      }

      .grid-right-icon {
        margin-left: 20rpx;
        margin-top: -20rpx;
      }
    }
  }

  .step {
    flex-direction: column;
    align-items: center;
  }

  .u-icon {
    margin-bottom: 20rpx;
  }
}

.faq-section {
  margin: 0 20rpx 20rpx;
  height: auto; /* 设置固定高度 */
  background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
  background-color: #ffffff;
  background-repeat: no-repeat;
  background-size: 100% 30%;
  padding: 0 20rpx;
  border-radius: 16rpx;
}

.faq-header {
  padding: 40rpx 0 20rpx 10rpx;
}

.quick-action-button {
  //background-image: url('https://huishou.8clc.com/static/images/quick-action-button.png');
  background-size: cover;
  background-repeat: no-repeat;
  height: 150rpx;
  width: 714rpx;
}

.title-box {
  margin-left: 10rpx;
  font-weight: bold;
}

.title-text {
  margin-left: 15rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.show-box {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.go-recycle-button {
  text-align: center;
  font-size: 48rpx;
  background: linear-gradient(45deg, #236af6, #7bb3f0); /* 渐变背景 */
  color: #fff;
  border-radius: 48rpx;
  padding: 20rpx;
  margin: 20rpx 30rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
  font-weight: bold;
  transition: all 0.3s ease;
  letter-spacing: 30rpx;
}
</style>
